<?php
// 应用公共文件

use app\common\service\AuthService;
use think\facade\Cache;
use think\facade\Filesystem;
use think\facade\Request;
use think\route\Url;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        $url = url($url, $vars, $suffix, $domain)->build();

        $url_data = parse_url($url);

        $url_path = $url_data['path'];

        $url_arr = explode('/', $url_path);

        $app_map = config('app.app_map');

        $app_name = array_search($url_arr[1], $app_map);

        if (!empty($app_name)) {
            $url_arr[1] = $app_name;
        }

        $url_path = implode('/', $url_arr);

        $url_data['path'] = $url_path;

        $url = unparse_url($url_data);

        return $url;
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value, $salt = '_encrypt')
    {
        $value = sha1('ming_' . $salt) . md5($value) . md5($salt) . sha1($value);
        return sha1($value);
    }
}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     * @deprecated 不建议使用，建议直接使用框架自带的log组件
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file,
            "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL,
            FILE_APPEND);

        $str = '';

        if (is_string($data)) {
            $str = $data;
        }
        else {
            if (is_array($data) || is_object($data)) {
                $str = print_r($data, true);
            }
            else {
                $str = var_export($data, true);
            }
        }

        $str . PHP_EOL;

        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null|bool|string $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null, $default = null)
    {

        if ($name === true) {
            $value = Cache::get('sysconfig_' . $group);

            if (empty($value)) {
                $value = \app\admin\model\system\SystemConfig::where('name', $group)->value('value');
                Cache::tag('sysconfig')->set('sysconfig_' . $group, $value);
            }
            if (is_null($value)) {
                return $default;
            }
            return $value;
        }

        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value         = \app\admin\model\system\SystemConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            }
            else {
                $value = \app\admin\model\system\SystemConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        if (is_null($value)) {
            return $default;
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }
}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check       = $authService->checkNode($node);
        return $check;
    }
}


function json_message($data = [], $code = 0, $msg = '')
{
    if (is_string($data)) {

        if (strpos($data, 'http') === 0 || strpos($data, '/') === 0) {
            $data = [
                'jump_to_url' => $data
            ];
        }
        else {

            $code = $code === 0 ? 500 : $code;
            $msg  = $data;
            $data = [];
        }
    }
    elseif ($data instanceof Url) {
        $data = [
            'jump_to_url' => (string)$data
        ];
    }

    return json([
        'code' => $code,
        'msg'  => $msg,
        'data' => $data
    ]);
}


if (!function_exists('unparse_url')) {

    function unparse_url($parsed_url)
    {
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
        $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
        $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
        $pass     = ($user || $pass) ? "$pass@" : '';
        $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
        return "$scheme$user$pass$host$port$path$query$fragment";
    }
}

if (!function_exists('ua_htmlspecialchars')) {
    function ua_htmlspecialchars($string)
    {

        if (is_null($string)) {
            $string = '';
        }

        return htmlspecialchars($string);
    }
}

if (!function_exists('ua_htmlentities')) {
    function ua_htmlentities($string)
    {

        if (is_null($string)) {
            $string = '';
        }

        return htmlentities($string);
    }
}

if (!function_exists('ua_htmlspecialchars_decode')) {
    function ua_htmlspecialchars_decode($string, $flag = ENT_QUOTES | ENT_SUBSTITUTE)
    {

        if (is_null($string)) {
            $string = '';
        }

        return htmlspecialchars_decode($string, $flag);
    }
}

if (!function_exists('build_upload_url')) {
    function build_upload_url($url, $upload_type = null)
    {

        if (is_null($upload_type)) {
            $upload_type = sysconfig('upload', 'upload_type', 'local_public');
        }
        return Filesystem::disk($upload_type)->url($url);
    }
}
if (!function_exists('exception')) {
    /**
     * 抛出异常处理
     *
     * @param string $msg 异常消息
     * @param integer $code 异常代码 默认为0
     * @param string $exception 异常类
     * @throws Exception
     */
    function exception(string $msg, int $code = 0, string $exception = '')
    {
        $e = $exception ?: '\think\Exception';
        throw new $e($msg, $code);
    }
}
if (!function_exists('addons_action')) {
    /**
     * 执行插件动作
     * 也可以用这种方式调用：addons_action('插件名/控制器/动作', [参数1,参数2...])
     * @param string $name 插件名
     * @param string $controller 控制器
     * @param string $action 动作
     * @param mixed $params 参数
     * @return mixed
     */
    function addons_action($name = '', $controller = '', $action = '', $params = [])
    {
        if (strpos($name, '/')) {
            $params = is_array($controller) ? $controller : (array)$controller;
            list($name, $controller, $action) = explode('/', $name);
        }
        if (!is_array($params)) {
            $params = (array)$params;
        }
        $class = "addons\\{$name}\\controller\\{$controller}";
        $obj   = new $class;
        return call_user_func_array([$obj, $action], $params);
    }
}
if (!function_exists('addons_config')) {
    /**
     * 获取或设置某个插件配置参数
     * @param string $name 插件名.配置名
     * @param string $value 设置值
     * @return mixed
     */
    function addons_config(string $name = '', array $value = [])
    {
        $addons = new \app\admin\model\system\SystemAddons;
        if ($value == []) {
            // 获取插件配置
            if (strpos($name, '.')) {
                list($name, $item) = explode('.', $name);
                return $addons->getConfig($name, $item);
            }
            else {
                return $addons->getConfig($name);
            }
        }
        else {
            return $addons->setConfig($name, $value);
        }
    }
}
if (!function_exists('get_addons_class')) {
    /**
     * 获取插件类名
     * @param string $name 插件名
     * @return string
     */
    function get_addons_class(string $name)
    {
        return "addons\\{$name}\\{$name}";
    }
}
if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP地址
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function get_client_ip(int $type = 0, bool $adv = false)
    {
        $type = $type ? 1 : 0;
        static $ip = null;
        if ($ip !== null) {
            return $ip[$type];
        }
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip = trim($arr[0]);
            }
            elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            }
            elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        }
        elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
if (!function_exists('get_order_sn')) {
    /** 
     * @Author: Bryant  
     * @Date: 2023-06-13 15:20:09 
     * @method post 
     * @title 生成订单号 
     */
    function get_order_sn($type = 'S')
    {
        //生成随机3位数字
        $rand = service\Str::randString(3, 1);
        //获取当前毫秒时间
        $msec = substr(get_msectime(), 10);
        //和当前时间组合得到订单号
        $orderSn = $type . date('YmdHis', time()) . $msec . $rand;

        return $orderSn;
    }
}
if (!function_exists('get_msectime')) {

    /** 
     * @Author: Bryant  
     * @Date: 2023-06-13 15:22:17 
     * @method post 
     * @title 返回当前的毫秒时间戳 
     */
    function get_msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    if (!function_exists('time_stamp_start')) {
        function time_stamp_start($m = 0,$d = 0,$y = 0)
        {
            return mktime(0,0,0,date('m')-$m,date('d')-$d,date('Y')-$y);
        }
    }
    if (!function_exists('time_stamp_end')) {
        function time_stamp_end($m = 0,$d = 0,$y = 0)
        {
            return mktime(23,59,59,date('m')-$m,date('d')-$d,date('Y')-$y);
        }
    }
}
if (!function_exists('friend_date')) {

    /** 
     * @Author: Bryant  
     * @Date: 2024-05-09 14:51:42 
     * @method post 
     * @title 时间转换 
     */
    function friend_date($time)
    {
        if (!$time)
            return false;
        $fdate = '';
        $d = time() - intval($time);
        $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
        $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
        $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
        $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
        $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
        $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
        $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
        if ($d == 0) {
            $fdate = '刚刚';
        } else {
            switch ($d) {
                case $d < $atd:
                    $fdate = date('Y-m-d', $time);
                    break;
                case $d < $td:
                    $fdate = '后天' . date('H:i', $time);
                    break;
                case $d < 0:
                    $fdate = '明天' . date('H:i', $time);
                    break;
                case $d < 60:
                    $fdate = $d . '秒前';
                    break;
                case $d < 3600:
                    $fdate = floor($d / 60) . '分钟前';
                    break;
                case $d < $dd:
                    $fdate = floor($d / 3600) . '小时前';
                    break;
                case $d < $yd:
                    $fdate = '昨天' . date('H:i', $time);
                    break;
                case $d < $byd:
                    $fdate = '前天' . date('H:i', $time);
                    break;
                case $d < $md:
                    $fdate = date('m/d日 H:i', $time);
                    break;
                case $d < $ld:
                    $fdate = date('m/d', $time);
                    break;
                default:
                    $fdate = date('Y-m-d', $time);
                    break;
            }
        }
        return $fdate;
    }
}
function certify($name,$idcard)
{
    $host = "https://jmidcardv1.market.alicloudapi.com";
    $path = "/idcard/validate";
    $method = "POST";
    $appcode = "27dc73507c4149fc837263dbeb4be469";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    //根据API的要求，定义相对应的Content-Type
     array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
    $querys = "";
    $bodys = "idCardNo=".$idcard."&name=".$name;
    $url = $host . $path;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_HEADER, 0); // 不返回HTTP头部信息
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response);
}
/** 
     * @Author: KoBe 
     * @Date: 2022-08-15 13:42:52 
     * @Desc: 获取经纬度 
     */
    function getLat($address)
    {
        //创建应用生成的key
        $key = '2b43a6a2ce6ded1da583f591d732334f';
        // $key = '8260d8a5fe6a401ccb3941e0a13ac01e';
        //根据开发文档获取经纬度
        $url = "https://restapi.amap.com/v3/geocode/geo?key=" . $key . "&address=" . $address;
        $json = file_get_contents($url);
        $GaoDeArr = json_decode($json,true);
        if ($GaoDeArr['infocode'] != '10000'){
            return [
                'lat' => '',
                'lng' => ''
            ];
        }
        $location = explode(',' , $GaoDeArr['geocodes'][0]['location']);
        return [
            'lat' => $location[1],
            'lng' => $location[0]
        ];
    }